package com.wendy.common.core.json.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wendy.common.core.constant.BaseDbType;
import com.wendy.common.core.constant.BaseType;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

/**
 * @Author: ALEX WANG
 * @Date: 2020/9/27 16:09
 */
public class ToJsonObject <E> implements BaseDbType<String>, BaseType<E>, Serializable {
    private E object;

    public E getObject() {
        return object;
    }

    public void setObject(E object) {
        this.object = object;
    }

    @Override
    public String selectDbTypeValue() {
        ObjectMapper mapper= new ObjectMapper();

        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void addDbTypeValue(String s) {
        if(StringUtils.isBlank(s)){
            return;
        }
        ObjectMapper mapper= new ObjectMapper();
        try {
            object = mapper.readValue(s, new TypeReference<E>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public E selectTypeValue() {
        return object;
    }

    @Override
    public void addTypeValue(E e) {
        object=e;
    }
}
